import OlMap from 'ol/Map'
import View from 'ol/View'
import { defaults } from 'ol/interaction'
import { getCenter } from 'ol/extent'
import layerCreator from './layerCreator'

export default function mapCreator (targetEl, mapConfig, baseMap, layerConfig, mapControls) {
  // console.log('mapCreator mapConfig-----------------------:', mapConfig)
  const view = {
    projection: mapConfig.mapProjection,
    maxZoom: mapConfig.maxZoom,
    minZoom: mapConfig.minZoom
  }

  // 如果不指定外包范围 则必须指定这两项
  if (mapConfig.defaultMapViewCenter) view.center = mapConfig.defaultMapViewCenter
  if (mapConfig.defaultMapViewLevel) view.zoom = mapConfig.defaultMapViewLevel

  const map = new OlMap({
    target: targetEl,
    interactions: defaults({ doubleClickZoom: false }),
    view: new View(view)
  })

  // 如果指定了外包范围,则根据外包范围自适应地图大小和中心点; view.center 和 view.zoom 不起作用
  if (mapConfig.extent && mapConfig.extent.length === 4) {
    var r = map.getView().getResolutionForExtent(mapConfig.extent, map.getSize())
    map.getView().setResolution(r)
    map.getView().setCenter(getCenter(mapConfig.extent))
  }

  // 初始化底图
  for (var i = 0; i < baseMap.length; i++) {
    let layer = null
    if (baseMap[i].layers) {
      layer = layerCreator.createGroup(baseMap[i])
    } else {
      layer = layerCreator.createLayer(baseMap[i])
    }
    if (layer) map.addLayer(layer)
  }

  // 初始化图层或图层组
  for (let i = 0; i < layerConfig.length; i++) {
    let layer = null
    if (layerConfig[i].layers) {
      layer = layerCreator.createGroup(layerConfig[i])
    } else {
      layer = layerCreator.createLayer(layerConfig[i])
    }
    if (layer) map.addLayer(layer)
  }

  // 初始化控件
  if (mapControls) {
    for (let i = 0; i < mapControls.length; i++) {
      map.addControl(mapControls[i])
    }
  }

  return map
}
